<template>
  <div id='alarm-rpt'>
    <el-tabs v-model='activeTab'>
      <!-- Tab 1: 文件上传 -->
      <el-tab-pane label='上传文件' name='upload'>
        <div class='upload-tab'>
          <label for='file-upload' class='file-label'>选择文件:</label>
          <input
            id='file-upload'
            type='file'
            @change='handleFileChange'
            ref='fileInput'
            style='margin-bottom: 10px'
          />
          <p v-if='fileName' class='file-name'>已选择文件: {{ fileName }}</p>
          <el-button type='primary' @click='uploadFile' :disabled='!selectedFile'>
            上传文件
          </el-button>
          <div v-if='uploadResponse' class='response'>
            <p><strong>上传结果:</strong></p>
            <p>{{ uploadResponse.message.result_text }}</p>
            <p>
              <strong>下载链接:</strong>
              <a :href='uploadResponse.message.data[0].download_url' target='_blank'>
                {{ uploadResponse.message.data[0].download_url }}
              </a>
            </p>
          </div>
        </div>
      </el-tab-pane>

      <!-- Tab 2: 文件列表 -->
      <el-tab-pane label='文件列表' name='filelist'>
        <div class='filelist-tab'>
          <el-button type='primary' @click='fetchFileList'>获取文件列表</el-button>
          <div v-if='isProcessing' class='processing'>
            <el-spinner type='circle'></el-spinner>
            <span>正在处理中，请稍候...</span>
          </div>
          <el-table :data='sortedFileList' border style='margin-top: 20px'>
            <el-table-column prop='file_name' label='文件名' />
            <el-table-column prop='file_ctime' label='创建时间' />
            <el-table-column prop='file_type' label='文件类型' />
            <el-table-column prop='file_size' label='文件大小' />
            <el-table-column label='操作'>
              <template #default='{ row }'>
                <el-button type='success' size='mini' @click='downloadFile(row.file_name)'>
                  下载
                </el-button>
                <el-button
                  type='danger'
                  size='mini'
                  @click='openDeleteDialog(row.file_name)'
                  style='margin-left: 5px'
                >
                  删除
                </el-button>
                <el-button
                  type='warning'
                  size='mini'
                  :disabled='processingFile === row.file_name'
                  @click='fillAlarmReason(row.file_name)'
                  style='margin-left: 5px'
                >
                  填充告警原因
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 删除确认对话框 -->
        <el-dialog
          title='确认删除'
          :visible.sync='deleteDialogVisible'
          width='400px'
          @close='resetDeleteDialog'
        >
          <p>确定要删除文件 "{{ fileToDelete }}" 吗？</p>
          <span slot='footer' class='dialog-footer'>
            <el-button @click='deleteDialogVisible = false'>取消</el-button>
            <el-button type='danger' @click='confirmDeleteFile'>确认</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>

      <!-- Tab 3: 下载文件 -->
      <el-tab-pane label='文件下载' name='download'>
        <div class='download-tab'>
          <el-input
            v-model='filenameToDownload'
            placeholder='输入文件名'
            style='margin-bottom: 10px'
          />
          <el-button type='primary' @click='downloadFile(filenameToDownload)'>
            下载文件
          </el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'AlarmRpt',
  data () {
    return {
      activeTab: 'upload',
      selectedFile: null,
      fileName: '', // 显示选中文件名
      uploadResponse: null,
      fileList: [], // 原始文件列表
      filenameToDownload: '',
      deleteDialogVisible: false, // 删除对话框显示状态
      fileToDelete: '', // 当前要删除的文件名
      isProcessing: false, // 是否有文件正在处理中
      processingFile: null // 当前正在处理的文件名
    }
  },
  computed: {
    // 按时间排序的文件列表
    sortedFileList () {
      return this.fileList.slice().sort((a, b) => {
        return new Date(b.file_ctime) - new Date(a.file_ctime)
      })
    }
  },
  methods: {
    handleFileChange (event) {
      const file = event.target.files[0]
      if (file) {
        this.selectedFile = file
        this.fileName = file.name
      }
      this.$refs.fileInput.value = null
    },
    uploadFile () {
      if (!this.selectedFile) {
        this.$message.error('请选择一个文件')
        return
      }
      const formData = new FormData()
      formData.append('file', this.selectedFile)
      axios
        .post(process.env.API_ROOT + '/ns_alarm_rpt/upload', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        .then((response) => {
          this.uploadResponse = response.data
          this.selectedFile = null
          this.fileName = ''
        })
        .catch((error) => {
          console.error('上传失败:', error)
        })
    },
    fetchFileList () {
      axios
        .post(
          process.env.API_ROOT + '/ns_alarm_rpt/filelist',
          { dir_name: './app1/download' },
          { headers: { 'Content-Type': 'application/json' } }
        )
        .then((response) => {
          this.fileList = response.data.message.data || []
        })
        .catch((error) => {
          console.error('获取文件列表失败:', error)
        })
    },
    openDeleteDialog (fileName) {
      this.fileToDelete = fileName
      this.deleteDialogVisible = true
    },
    resetDeleteDialog () {
      this.fileToDelete = ''
    },
    confirmDeleteFile () {
      const payload = {
        dir_name: './app1/download',
        file_name: this.fileToDelete
      }
      axios
        .post(process.env.API_ROOT + '/ns_alarm_rpt/filedelete', payload, {
          headers: { 'Content-Type': 'application/json' }
        })
        .then((response) => {
          this.$message.success(response.data.message.result_text)
          this.fetchFileList()
          this.deleteDialogVisible = false
        })
        .catch((error) => {
          console.error('删除失败:', error)
        })
    },
    fillAlarmReason (fileName) {
      this.isProcessing = true
      this.processingFile = fileName
      const payload = {
        dir_name: './app1/download',
        file_name: fileName
      }
      axios
        .post(process.env.API_ROOT + '/ns_alarm_rpt/filefill', payload, {
          headers: { 'Content-Type': 'application/json' }
        })
        .then((response) => {
          this.$message.success(response.data.message.result_text)
        })
        .catch((error) => {
          console.error('填充告警原因失败:', error)
        })
        .finally(() => {
          this.isProcessing = false
          this.processingFile = null
        })
    },
    downloadFile (filename) {
      if (!filename) {
        this.$message.error('请输入文件名')
        return
      }
      const url = process.env.API_ROOT + `/ns_alarm_rpt/download/${encodeURIComponent(
        filename
      )}`
      axios
        .get(url, { responseType: 'blob' })
        .then((response) => {
          const link = document.createElement('a')
          link.href = URL.createObjectURL(new Blob([response.data]))
          link.download = filename
          link.click()
        })
        .catch((error) => {
          console.error('下载失败:', error)
        })
    }
  }
}
</script>

<style scoped>
.upload-tab,
.filelist-tab,
.download-tab {
  padding: 20px;
}

.response {
  margin-top: 20px;
}

.file-label {
  display: block;
  font-weight: bold;
  margin-bottom: 10px;
}

.file-name {
  margin: 10px 0;
  color: #666;
}

.processing {
  display: flex;
  align-items: center;
  margin-top: 10px;
  font-size: 16px;
}

.processing el-spinner {
  margin-right: 10px;
}
</style>
